package me.blog.markan.webserver.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import markan.blog.me.util.MimetypesFileTypeMap;

import org.ygsoft.webserver.AbstractService;
import org.ygsoft.webserver.PLogging;
import org.ygsoft.webserver.ProtocolHelper;
import org.ygsoft.webserver.ResourceDescription;

public class StaticResourceService extends AbstractService {

	private static final String DEFAULT_FILE_PATH = "index.html";
	private static final int bufSize = 8192;
	static final String extension = "*";

	public StaticResourceService() {
		PLogging.printv(PLogging.INFO, "Init Static resource container ..");
	}

	@Override
	public String getRequestExtension() {
		return extension;
	}

	@Override
	public void service() {
		ResourceDescription rd = this.request.getParsedMainHeader();
		if (rd != null) {

			String fileName = rd.getResName();

			try {
				InputStream assetFile = new FileInputStream(new File(fileName));

				if (assetFile.available() > 0) {
					PLogging.printv(PLogging.INFO, "[Request Static Res]" + fileName);
					this.response = ProtocolHelper.getDefaultXResponse(this.response);
					this.response.setAttribute("Content-Type", new MimetypesFileTypeMap().getContentMimeType(fileName));
					this.response.setAttribute("Content-Length", String.valueOf(assetFile.available()));

					String header = this.response.getRawHeaderText();
					PLogging.printv(PLogging.DEBUG, "Send Header >" + header);

					OutputStream os = this.response.getOutputStream();
					os.write(header.getBytes());

					byte[] buf = new byte[bufSize];
					int c = 0;
					while ((c = assetFile.read(buf)) > 0) {
						os.write(buf, 0, c);
					}
					os.flush();
					assetFile.close();
				} else {
					PLogging.printv(PLogging.DEBUG,
							"Cannot find resource .. send 404 ..");
					try {
						this.response.getOutputStream().write(
								ProtocolHelper.getDefaultErrorHeader("500")
										.getBytes());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
